package com.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.web.multipart.MultipartFile;

import com.vframework.common.constant.BusinessConstant;

public class UploadUtil {
	
	private UploadUtil(){
	}
	
	/**
	 * 上传图片<br/>
	 * 图片会被上传至用户上下文的attacment文件夹的subFolder子文件夹中<br/>
	 * 
	 * @param MultipartFile  SpringMVC 图片file对象
	 * @param realFileName 上传的图片原名
	 * @param subFolder  子文件夹名
	 * @return 
	 * @since 上传后的本地路径，如:fs:/attachment/goods/2001010101030.jpg<br/>
	 * 
	 */
	public static Map<?, ?> upload(MultipartFile file, String realFileName, String subFolder, String permission) {
	    Map<String, String> resultMap = new HashMap<String, String>();
		if(file == null || realFileName == null) throw new IllegalArgumentException("file or filename object is null");
		if(subFolder == null)throw new IllegalArgumentException("subFolder is null");
		
		if(!FileUtil.isAllowUp(realFileName)) throw new IllegalArgumentException("不被允许的上传文件类型");
		
		String fileName = null;
		String filePath = "";
		String fileSize = Long.toString(file.getSize());
		String ext = FileUtil.getFileExt(realFileName);
		fileName = DateUtil.toString(new Date(), "yyyyMMddHHmmss") + StringUtil.getRandStr(4) + "." + ext;
		if ("1".equals(permission)) {
		    filePath =  BusinessConstant.SOURCE_PRIVATE_PATH + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR + BusinessConstant.FILE_SEPARATOR;
		} else {
		    filePath =  BusinessConstant.SOURCE_PUBLIC_PATH + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR + BusinessConstant.FILE_SEPARATOR;
		}
		if(subFolder != null){
			filePath += subFolder + BusinessConstant.FILE_SEPARATOR;
		}
		
		String path  = BusinessConstant.FILE_STORE_PREFIX + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR +
		        BusinessConstant.FILE_SEPARATOR + (subFolder==null ? "" : subFolder) + BusinessConstant.FILE_SEPARATOR + fileName;
		filePath += fileName;
		try {
            FileUtil.createFile(file.getInputStream(), filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
		resultMap.put("fileName", realFileName);
		resultMap.put("fileType", ext);
		resultMap.put("path", path);
		resultMap.put("fileSize", fileSize);
		return resultMap;
	}
	
	/**
	 * 上传图片<br/>
	 * 图片会被上传至用户上下文的attacment文件夹的subFolder子文件夹中<br/>
	 * 
	 * @param file  图片file对象
	 * @param fileFileName 上传的图片原名
	 * @param subFolder  子文件夹名
	 * @return 
	 * @since 上传后的本地路径，如:fs:/attachment/goods/2001010101030.jpg<br/>
	 * 
	 */
	public static Map<?, ?> upload(File file, String fileFileName, String subFolder) {
	    Map<String, String> resultMap = new HashMap<String, String>();
	    if(file == null || fileFileName == null) throw new IllegalArgumentException("file or filename object is null");
	    if(subFolder == null)throw new IllegalArgumentException("subFolder is null");
	    
	    if(!FileUtil.isAllowUp(fileFileName)) throw new IllegalArgumentException("不被允许的上传文件类型");
	    
	    String fileName = null;
	    String filePath = "";
	    String fileSize = Long.toString(file.length());
	    
	    String ext = FileUtil.getFileExt(fileFileName);
	    fileName = DateUtil.toString(new Date(), "yyyyMMddHHmmss") + StringUtil.getRandStr(4) + "." + ext;
	    
	    filePath = BusinessConstant.SOURCE_PUBLIC_PATH + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR + BusinessConstant.FILE_SEPARATOR;
	    if(subFolder != null){
	        filePath += subFolder + BusinessConstant.FILE_SEPARATOR;
	    }
	    
	    String path = BusinessConstant.FILE_STORE_PREFIX + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR +
	            BusinessConstant.FILE_SEPARATOR + (subFolder==null ? "" : subFolder) + BusinessConstant.FILE_SEPARATOR + fileName;
	    filePath += fileName;
        FileUtil.createFile(file, filePath);
        
        resultMap.put("fileName", fileName);
        resultMap.put("fileType", ext);
        resultMap.put("path", path);
        resultMap.put("fileSize", fileSize);
        return resultMap;
	}
	/**
	 * 上传图片<br/>
	 * 文件上传至指定文件位置<br/>
	 * 
	 * @param file  图片file对象
	 * @param fileName 上传的文件位置
	 * 
	 */
	public static void upload(File file, String fileName) {
		if(file == null || fileName == null) throw new IllegalArgumentException("file or filename object is null");
		
		if(!FileUtil.isAllowUp(fileName)) throw new IllegalArgumentException("不被允许的上传文件类型");

		fileName = replaceFilePath(fileName);
		FileUtil.createFile(file, fileName);
	}
	/**
	 * 替换文件<br/>
	 * 将原文件替换<br/>
	 * @param file  新文件 对象
	 * @param fileName 原文件位置
	 * 
	 */
	public static void replace(File file, String fileName) {
		if(file == null || fileName == null) throw new IllegalArgumentException("file or filename object is null");
		if(!FileUtil.isAllowUp(fileName)) throw new IllegalArgumentException("不被允许的上传文件类型");

		fileName = replaceFilePath(fileName);
		deleteFile(fileName);
		FileUtil.createFile(file, fileName);
	}
	
	public static String replaceFilePath(String path){
		if(StringUtil.isEmpty(path)) return path;
		return path.replaceAll(BusinessConstant.FILE_STORE_PREFIX, BusinessConstant.SOURCE_PUBLIC_PATH);
	}
	
	public static String replaceFilePrivatePath(String path){
	    if(StringUtil.isEmpty(path)) return path;
	    return path.replaceAll(BusinessConstant.FILE_STORE_PREFIX, BusinessConstant.SOURCE_PRIVATE_PATH);
	}

	public static String replacePath(String path){
		if(StringUtil.isEmpty(path)) return path;
		return path.replaceAll(BusinessConstant.FILE_STORE_PREFIX, BusinessConstant.SOURCE_SERVER_DOMAIN);
	}
	
	public static String replacePrivatePath(String path){
		if(StringUtil.isEmpty(path)) return path;
		return path.replaceAll(BusinessConstant.FILE_STORE_PREFIX, BusinessConstant.SOURCE_PRIVATE_DOMAIN);
	}
	
	/**
	 * 上传图片并生成缩略图
	 * 图片会被上传至用户上下文的attacment文件夹的subFolder子文件夹中<br/>
	 * 
	 * @param file  图片file对象
	 * @param fileFileName 上传的图片原名
	 * @param subFolder  子文件夹名
	 * @param width 缩略图的宽
	 * @param height 缩略图的高
	 * @return 上传后的图版全路径，如:http://static.eop.com/user/1/1/attachment/goods/2001010101030.jpg<br/>
	 * 返回值为大小为2的String数组，第一个元素为上传后的原图全路径，第二个为缩略图全路径
	 */
	public static String[] upload(File file, String fileFileName, String subFolder, int width, int height){
		if(file == null || fileFileName == null) throw new IllegalArgumentException("file or filename object is null");
		if(subFolder == null)throw new IllegalArgumentException("subFolder is null");
		String fileName = null;
		String filePath = "";
		String [] path = new String[2];
		if(!FileUtil.isAllowUp(fileFileName)) throw new IllegalArgumentException("不被允许的上传文件类型");
		
		String ext = FileUtil.getFileExt(fileFileName);
		fileName = DateUtil.toString(new Date(), "yyyyMMddHHmmss") + StringUtil.getRandStr(4) + "." + ext;
		
		filePath =  BusinessConstant.SOURCE_PUBLIC_PATH + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR + BusinessConstant.FILE_SEPARATOR;
		if(subFolder != null){
			filePath += subFolder + BusinessConstant.FILE_SEPARATOR;
		}
		path[0] = BusinessConstant.SOURCE_SERVER_DOMAIN + BusinessConstant.FILE_SEPARATOR + BusinessConstant.ATTACHMENT_DIR + BusinessConstant.FILE_SEPARATOR
				+ (subFolder == null ? "" : subFolder) + BusinessConstant.FILE_SEPARATOR + fileName;
		filePath += fileName;
		FileUtil.createFile(file, filePath);
		String thumbName= getThumbPath(filePath, "_thumbnail");
		
//		IThumbnailCreator thumbnailCreator = ThumbnailCreatorFactory.getCreator(filePath, thumbName);
//		thumbnailCreator.resize(width, height);
		path[1] = getThumbPath(path[0], "_thumbnail");
		return path;
	}
	
	/**
	 * 删除某个上传的文件
	 * @param filePath 文件全路径如：http://static.eop.com/user/1/1/attachment/goods/2001010101030.jpg
	 */
	public static void deleteFile(String filePath){
		filePath = replacePath(filePath);
		filePath = filePath.replaceAll(BusinessConstant.SOURCE_SERVER_DOMAIN, BusinessConstant.SOURCE_PUBLIC_PATH);
		FileUtil.delete(filePath);
	}
	
	/**
	 * 删除某个上传的文件
	 * @param filePath 文件全路径如：http://static.eop.com/user/1/1/attachment/goods/2001010101030.jpg
	 */
	public static void deleteFileAndThumb(String filePath){
		filePath = filePath.replaceAll(BusinessConstant.SOURCE_SERVER_DOMAIN, BusinessConstant.SOURCE_PUBLIC_PATH);
		FileUtil.delete(filePath);
		FileUtil.delete(getThumbPath(filePath, "_thumbnail"));
	}
	
	/**
	 * 转换图片的名称
	 * @param filePath  如：http://static.eop.com/user/1/1/attachment/goods/2001010101030.jpg
	 * @param shortName 
	 * @return
	 */
	public static String getThumbPath(String filePath, String shortName) {
		String pattern = "(.*)([\\.])(.*)";
		String thumbPath = "$1" + shortName + "$2$3";
		Pattern p = Pattern.compile(pattern, 2 | Pattern.DOTALL);
		Matcher m = p.matcher(filePath);
		if (m.find()) {
			String s = m.replaceAll(thumbPath);
			return s;
		}
		return null;
	}
}